const path = require('path');
const Router = require('koa-router');
const send = require('koa-send');
const router = new Router();

const excel = require('../excel/excel');

const contentLogic = require('../business-logic/content');

router.get('/contents', async(ctx, next) => {
    let query = ctx.request.query;
    let filter = {};
    if (query.dateStart || query.dateEnd) {
        filter.date = {};
    }
    if (query.dateStart) {
        filter.date.$gt = query.dateStart;
    }
    if (query.dateEnd) {
        filter.date.$lt = query.dateEnd;
    }
    let contents = await contentLogic.query(query.pageNum, query.pageSize, filter);
    let total = await contentLogic.total();
    ctx.send({
        code: 200,
        data: {
            contents: contents,
            total: total
        }
    })
})

router.get('/contents-export', async(ctx, next) => {
    let { dateStart, dateEnd } = ctx.request.query;
    if (!dateStart || !dateEnd) {
        ctx.send({
            code: 403,
            msg: 'params is wrong'
        })
    }
    dateStart = new Date(dateStart);
    dateEnd = new Date(dateEnd);
    dateEnd.setDate(dateEnd.getDate() + 1)
    let filter = {
        date: {
            $gt: dateStart,
            $lt: dateEnd
        }
    }
    let contents = await contentLogic.query(1, 10000, filter);
    let filePath = await excel.exportExcel(contents);
    let fileName = path.basename(filePath);
    ctx.attachment(fileName);
    await send(ctx, filePath, { root: path.resolve(__dirname, '../') });
})

module.exports = router;